package com.android.systemui.ios;

import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.ServiceConnection;
import android.content.pm.ActivityInfo;
import android.graphics.PixelFormat;
import android.os.IBinder;
import android.os.RemoteException;
import android.provider.Settings;
import android.view.Gravity;
import android.view.WindowManager;

import com.android.systemui.ios.views.ShadeBarWindowView;

public class ShadeBarService extends Service implements ServiceConnection {

    private ShadeBarWindowView mMainView;
    private WindowManager mWindowManager;
    private WindowManager.LayoutParams mParams;

    private GuardServiceStub mService;
    private ISystemGuardService mISystemGuardService;

    private ShadeBarController mController;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();

        Intent intent = new Intent("android.ios.SYSTEM_GUARD_SERVICE");
        intent.setPackage("com.android.systemui");
        bindService(intent, this, BIND_AUTO_CREATE);

        mParams = new WindowManager.LayoutParams();
        mParams.x = 0;
        mParams.y = 0;
        mParams.width = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.height = WindowManager.LayoutParams.MATCH_PARENT;
        mParams.flags = WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN
                | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION
                | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
                | WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
                | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
        mParams.alpha = 1.0f;
        mParams.format = PixelFormat.TRANSPARENT;
        mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;//TYPE_STATUS_BAR_PANEL
        mParams.screenOrientation = ActivityInfo.SCREEN_ORIENTATION_USER;
        mParams.gravity = Gravity.TOP;

        mController = new ShadeBarController(this);
        mController.create();
        mController.setParams(mParams);
        mMainView = mController.getWindowView();
        mWindowManager = mController.getWindowManager();

        if (!Constants.KEYGUARD_ENABLE || Settings.Global.getInt(getContentResolver(), Settings.Global.DEVICE_PROVISIONED, 0) != 1) {
            mParams.alpha = 0.0f;
            mParams.gravity = Gravity.TOP;
            mParams.height = 1;
            Constants.isExpanded = false;
        }

        mWindowManager.addView(mMainView, mParams);

        IntentFilter filter = new IntentFilter();
        filter.addAction(Intent.ACTION_SCREEN_ON);
        filter.addAction(Intent.ACTION_SCREEN_OFF);
        registerReceiver(mBroadcastReceiver, filter);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWindowManager != null) {
            mWindowManager.removeView(mMainView);
        }
        if (mController != null) {
            mController.removeCallback(mGuardCallback, mStatusBarWindowCallback);
        }
        unbindService(this);
        unregisterReceiver(mBroadcastReceiver);
    }

    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mISystemGuardService = ISystemGuardService.Stub.asInterface(service);
        mService = new GuardServiceStub(mISystemGuardService);
        mService.setNavVisible(1);
        mController.setService(mService);
        mController.addCallback(mGuardCallback, mStatusBarWindowCallback);
        mService.requestLock(2);
        mMainView.setShowLockIcon(mService.isLocked());
    }

    @Override
    public void onServiceDisconnected(ComponentName name) {

    }

    private final BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            final String action = intent.getAction();
            if (Intent.ACTION_SCREEN_ON.equals(action)) {
                if (Constants.KEYGUARD_ENABLE) {
                    if (mService != null && mService.isLocked() && Settings.System.getInt(getContentResolver(), "iphone_face_unlock_enable", 0) == 1) {
                        mMainView.setFacePreviewEnable(true);
                    }
                }
            } else if (Intent.ACTION_SCREEN_OFF.equals(action)) {
                if (Constants.KEYGUARD_ENABLE) {
                    mParams.alpha = 1.0f;
                    mParams.gravity = Gravity.TOP;
                    mParams.height = WindowManager.LayoutParams.MATCH_PARENT;
                    mWindowManager.updateViewLayout(mMainView, mParams);
                    mMainView.resetKeyguard();
                    mMainView.setFacePreviewEnable(false);
                    KeyguardActivity.show(context);
                    Constants.isExpanded = true;
                    if (mService != null) {
                        mService.setNavVisible(1); // 0:Normal, 1:Disable gesture nav bar
                        mService.requestLock(2);
                        mMainView.setShowLockIcon(mService.isLocked());
                    }
                } else {
                    mParams.alpha = 0.0f;
                    mParams.gravity = Gravity.TOP;
                    mParams.height = 1;
                    mWindowManager.updateViewLayout(mMainView, mParams);
                    mMainView.resetKeyguard();
                    mMainView.setFacePreviewEnable(false);
                    KeyguardActivity.hide(context);
                    Constants.isExpanded = false;
                }
            }
        }
    };

    private final ISystemGuardChangedCallback mGuardCallback = new ISystemGuardChangedCallback.Stub() {

        @Override
        public void onDisturbChanged(boolean open) throws RemoteException {
            mController.getGuardCallback().onDisturbChanged(open);
        }

        @Override
        public void onBrightnessChanged(boolean auto, int brightness) throws RemoteException {
            mController.getGuardCallback().onBrightnessChanged(auto, brightness);
        }

        @Override
        public void onAirplaneModeChanged(boolean open) throws RemoteException {
            mController.getGuardCallback().onAirplaneModeChanged(open);
        }

        @Override
        public void onHotspotStateChanged(boolean enabled, int numDevices) throws RemoteException {
            mController.getGuardCallback().onHotspotStateChanged(enabled, numDevices);
        }

        @Override
        public void onGpsChanged(boolean open, boolean active) throws RemoteException {
            mController.getGuardCallback().onGpsChanged(open, active);
        }

        @Override
        public void onBluetoothChanged(boolean open, boolean connected, String name) throws RemoteException {
            mController.getGuardCallback().onBluetoothChanged(open, connected, name);
        }

        @Override
        public void onWifiChanged(boolean open, boolean connected, int signal, int network, String name) throws RemoteException {
            mController.getGuardCallback().onWifiChanged(open, connected, signal, network, name);
        }

        @Override
        public void onSimStateChanged(int count, int subId, boolean insert, int signal, int network, int dataType, String name) throws RemoteException {
            mController.getGuardCallback().onSimStateChanged(count, subId, insert, signal, network, dataType, name);
        }

        @Override
        public void onTorchChanged(boolean available, boolean open) throws RemoteException {
            mController.getGuardCallback().onTorchChanged(available, open);
        }

        @Override
        public void onAudioStateChanged(int stream, int volume, boolean silent, boolean vibrate) throws RemoteException {
            mController.getGuardCallback().onAudioStateChanged(stream, volume, silent, vibrate);
        }

        @Override
        public void onScreenAutoRotationChanged(boolean open) throws RemoteException {
            mController.getGuardCallback().onScreenAutoRotationChanged(open);
        }

        @Override
        public void onScreenRecordingChanged(int state, int time) throws RemoteException {
            mController.getGuardCallback().onScreenRecordingChanged(state, time);
        }

        @Override
        public void onBatteryChanged(int level, boolean pluggedIn, boolean charging, boolean powerSave) throws RemoteException {
            mController.getGuardCallback().onBatteryChanged(level, pluggedIn, charging, powerSave);
        }

        @Override
        public void onNotificationChanged(int action, String msgJson) throws RemoteException {
            mController.getGuardCallback().onNotificationChanged(action, msgJson);
        }
    };

    private final IStatusBarWindowChangedCallback mStatusBarWindowCallback = new IStatusBarWindowChangedCallback.Stub() {

        @Override
        public void onWindowHeightChanged(int height, boolean keyguard, boolean occluded) throws RemoteException {
            mController.getStatusBarWindowCallback().onWindowHeightChanged(height, keyguard, occluded);
        }

        @Override
        public void onDragWindowMoved(int action, float x, float y, float velocityX, float velocityY) throws RemoteException {
            mController.getStatusBarWindowCallback().onDragWindowMoved(action, x, y, velocityX, velocityY);
        }

        @Override
        public void onDirectionChanged(int rotation, int width, int height) throws RemoteException {
            mController.getStatusBarWindowCallback().onDirectionChanged(rotation, width, height);
        }

        @Override
        public void onThemeChanged(boolean dark) throws RemoteException {
            mController.getStatusBarWindowCallback().onThemeChanged(dark);
        }

        @Override
        public void onVerifyFaceIdResult(int state, int progress) throws RemoteException {
            mController.getStatusBarWindowCallback().onVerifyFaceIdResult(state, progress);
        }
    };
}
